<template>
  <Header :activeIndex="activeIndex" />
  <el-container style="margin: 0 50px">
    <el-main>
      <el-table
        :data="orders"
        style="min-width: 100%; height: 100vh; margin-top: 10px"
      >
        <el-table-column prop="id" label="订单编号"></el-table-column>
        <el-table-column prop="product_id" label="商品ID"></el-table-column>
        <el-table-column prop="user_id" label="购买用户ID"></el-table-column>
        <el-table-column prop="status" label="订单状态"></el-table-column>
        <el-table-column prop="purchase_date" label="购买时间">
          <template v-slot="scope">
            {{ formattedTime(scope.row.purchase_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="收货地"></el-table-column>
        <el-table-column prop="quantity" label="购买数量"></el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="searchParams.currentPage"
        v-model:page-size="searchParams.pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="parseInt(totalItems)"
        @size-change="orderList"
        @current-change="orderList"
      />
    </el-main>
  </el-container>
  <Footer />
</template>

<script>
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import { reactive, toRefs, ref } from 'vue'
import { orderListApi } from '@/api/order'
import { userApi } from '@/api/user'
import { useStore } from 'vuex'
export default {
  components: {
    Header,
    Footer
  },
  setup() {
    const data = reactive({
      totalItems: '',
      orders: [],
      user: {
        username: ''
      },
      searchParams: {
        currentPage: 1,
        pageSize: 5,
        userId: ''
      }
    })
    const activeIndex = ref('4')

    const store = useStore()

    const uInfo = store.state.uInfo.userInfo
    data.user.username = uInfo.username

    const orderList = () => {
      userApi(data.user).then((u) => {
        if (u) {
          data.searchParams.userId = u.data.id
          orderListApi(data.searchParams).then((res) => {
            if (res) {
              data.orders = res.data.data
              data.totalItems = res.data.total
            }
          })
        }
      })
    }
    orderList()
    return {
      ...toRefs(data),
      activeIndex,
      orderList
    }
  },
  methods: {
    formattedTime(Dtime) {
      if (Dtime) {
        const date = new Date(Dtime)
        const options = {
          year: 'numeric',
          month: 'long',
          day: 'numeric',
          hour: 'numeric',
          minute: 'numeric',
          second: 'numeric'
        }
        return date.toLocaleDateString('zh-CN', options)
      }
    }
  }
}
</script>

<style scoped></style>
